package com.yx.yinshanjinniu.utils;

import android.os.Handler;
import android.util.Log;

import com.yx.yinshanjinniu.application.MyApplication;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class WebSocketUtil {

    private volatile static WebSocketUtil webSocketUtil;

    private WebSocketUtil() {
    }

    public static synchronized WebSocketUtil getWebSocketUtil() {
        if (webSocketUtil == null) {
            synchronized (WebSocketUtil.class) {
                if (webSocketUtil == null) {
                    webSocketUtil = new WebSocketUtil();
                }
            }
        }
        return webSocketUtil;
    }


    private static final String TAG = "WebSocketUtil";

    private static final String WS = "wss://data.ly.mh.app.hblanyi.cn/ws/realTimeMessage";
//    private static final String WS = "ws://192.168.1.9:8081/ws/realTimeMessage";
    private WebSocket webSocket;
    private boolean isConnect = false;
    private String key = "26ad974629940bf88f6e0241554b7ab1";
    private Handler mHandler = new Handler();
    private Runnable mReconnectRunnable = new Runnable() {
        @Override
        public void run() {
            connect();
        }
    };


    private WebSocketListener wsListener = new WebSocketListener() {
        @Override
        public void onMessage(WebSocket webSocket, String text) {
            super.onMessage(webSocket, text);
//            Log.i(TAG, "webSocket收到消息==文字类型，消息内容====" + text);
            MyApplication.getApplication().setWebSocketJson(text);
        }

        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {
            super.onMessage(webSocket, bytes);
            Log.i(TAG, "webSocket收到消息===Byte类型");
        }

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            super.onOpen(webSocket, response);
            isConnect = true;
            Log.i(TAG, "webSocket连接成功");
            mHandler.removeCallbacks(mReconnectRunnable);
        }

        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            super.onClosed(webSocket, code, reason);
            isConnect = false;
            Log.i(TAG, "webSocket连接关闭");
            mHandler.postDelayed(mReconnectRunnable, 5000);
        }


        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            super.onClosing(webSocket, code, reason);
            Log.i(TAG, "webSocket正在关闭");
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            super.onFailure(webSocket, t, response);
            isConnect = false;
            Log.i(TAG, "webSocket连接失败" + t.getMessage());
            if (t instanceof SocketTimeoutException || t instanceof UnknownHostException){
                mHandler.postDelayed(mReconnectRunnable, 5000);
            }
        }
    };

    public WebSocket connect() {
        if (isConnect() && webSocket != null) {
            return webSocket;
        }
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder()
                .url(WS)
                .addHeader("sign", createSign())
                .build();
        webSocket = client.newWebSocket(request, wsListener);
        return webSocket;
    }

    public void send(String text) {
        if (webSocket != null) {
            webSocket.send(text);
        }
    }

    public void close() {
        if (webSocket != null) {
            webSocket.close(1000, "");
        }
    }

    public boolean isConnect() {
        return isConnect;
    }

    private String createSign() {
        long time = System.currentTimeMillis() / 1000;
        return time + "," + createMd5(time);
    }

    private String createMd5(long time){
        return Utils.md5(time + key);
    }

}
